﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;

namespace demo.Web.AzureTables
{
    public class AzureHelper
    {
        // valid characters for partition and row key
        private const string keyPattern = @"[^A-Za-z0-9\._;]*";

        /// <summary>
        /// scrub a partition or row key, replacing invalid characters with an underscore
        /// </summary>
        /// <param name="iptKey"></param>
        /// <param name="toUpper"></param>
        /// <returns></returns>
        public static string ScrubKey(string iptKey, bool toUpper = true)
        {
            char[] asChars = iptKey.ToCharArray();

            Regex rgx = new Regex(keyPattern);
            MatchCollection mc = rgx.Matches(iptKey);
            foreach (Match m in mc)
            {
                GroupCollection gc = m.Groups;
                foreach (Group g in gc)
                {
                    if (g.Length == 0)
                        continue;

                    for (int j = g.Index; j < g.Index + g.Length; ++j)
                        asChars[j] = '_';
                }
            }

            string newKey = new string(asChars);
            if (toUpper)
                newKey = newKey.ToUpper();

            return newKey;
        }

    }
}